package com.qihetimes.earthangel.config;

import com.qihetimes.earthangel.common.ApiException;
import com.qihetimes.earthangel.common.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理
 *
 * @author ：f4cklangzi@gmail.com
 * @date ：Created At 2021/12/4
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    
    @ResponseBody
    @ExceptionHandler(value = ApiException.class)
    public ResponseResult<String> handle(ApiException exception) {
        log.error("自定义异常", exception);
        return ResponseResult.failed(exception.getHttpStatus(), exception.getMessage());
    }
    
    @ResponseBody
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public ResponseResult<String> handle(HttpMessageNotReadableException exception) {
        log.error("参数格式错误", exception);
        return ResponseResult.failed("参数格式错误");
    }
    
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ResponseResult<String> handle(Exception exception) {
        log.error("服务器异常", exception);
        return ResponseResult.failed(HttpStatus.INTERNAL_SERVER_ERROR, exception.getMessage());
    }
}
